package com.ouroboroswiki.web.operation;

import java.io.IOException;
import java.util.Map;

import com.ouroboroswiki.core.AuthenticationException;
import com.ouroboroswiki.core.AuthenticationManager;
import com.ouroboroswiki.core.ContentException;
import com.ouroboroswiki.core.ContentPath;
import com.ouroboroswiki.core.ContentValidationException;
import com.ouroboroswiki.web.ContentOperation;

public class LoginContentOperation extends ContentOperationSupport implements ContentOperation {

	private static final String PARAMETER_USERNAME = "username";
	private static final String PARAMETER_PASSWORD = "password";
	
	private AuthenticationManager authenticationManager;

	public LoginContentOperation( AuthenticationManager authenticationManager ) {
		this.authenticationManager = authenticationManager;
	}
	
	@Override
	public String perform(Object[] principal, ContentPath uniqueId, Map parameters)
			throws ContentException, ContentValidationException, IOException {
		String username = getParameter( PARAMETER_USERNAME, parameters );
		String password = getParameter( PARAMETER_PASSWORD, parameters );
		try {
			Object p = authenticationManager.authenticate(username, password);				
			principal[0] = p;
		} catch( AuthenticationException ex ) {
			throw new ContentException( "unable to authenticate", ex );
		}
		return null;
	}
	
}
